package dao

import (
	"errors"
	"strings"
	"time"

	"github.com/segmentio/ksuid"
)

type Crontab struct {
	ID      string `json:"id" xorm:"pk notnull unique 'id'"`
	Name    string `json:"name" xorm:"'name'"`
	Created int64  `json:"created" xorm:"'created'"`
	Deleted int    `json:"deleted" xorm:"'deleted'"`

	Pinlv   string `json:"pinlv" xorm:"'pinlv'"`
	Week    string `json:"week" xorm:"default('') 'week'"`
	Day     string `json:"day" xorm:"default('') 'day'"`
	Times   string `json:"times" xorm:"'times'"`
	Crontab string `json:"crontab" xorm:"'crontab'"`
}

func (c *Crontab) Add() error {
	old := Crontab{}
	if bol, err := localdb.Where("pinlv=? and day=? and week=? and times=?", c.Pinlv, c.Day, c.Week, c.Times).Get(&old); err != nil {
		return err
	} else {
		if bol {
			return errors.New("相同计划已经存在")
		}
	}

	if name, err := CreateId("CRON", strings.ToUpper(c.Pinlv)); err != nil {
		return err
	} else {
		c.Name = name
	}
	c.ID = ksuid.New().String()
	c.Deleted = 0
	c.Created = time.Now().Unix()
	_, err := localdb.Insert(c)
	return err
}

func (c *Crontab) Update() error {
	_, err := localdb.ID(c.ID).AllCols().Update(c)
	return err
}

func (c *Crontab) Delete() error {
	_, err := localdb.ID(c.ID).Delete(new(Crontab))
	return err
}
